package com.partsoft.dits.dsm;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.util.Assert;

import com.partsoft.dits.utils.DbUtils;

public abstract class AbstractDsmSQLProviderFactory implements DsmSQLProviderFactory {
	
	private List<DsmOriginalSQLs> dsmOriginalSQLs = new LinkedList<DsmOriginalSQLs>();
	
	public AbstractDsmSQLProviderFactory() {}
	
	public List<DsmOriginalSQLs> getDsmOriginalSQLs() {
		synchronized (this) {
			if (dsmOriginalSQLs == null || dsmOriginalSQLs.equals(Collections.EMPTY_LIST)) {
				dsmOriginalSQLs = new LinkedList<DsmOriginalSQLs>();
			}
			return dsmOriginalSQLs;
		}
	}
	
	public void setDsmOriginalSQLs(List<DsmOriginalSQLs> dsmOriginalSQLs) {
		this.dsmOriginalSQLs = dsmOriginalSQLs;
	}
	
	public void addDsmOriginalSQLs(DsmOriginalSQLs orgs) {
		Assert.notNull(orgs);
		getDsmOriginalSQLs().add(orgs);
	}
	
	public void addDsmOriginalSQLs(InputStream ism) throws IOException {
		Assert.notNull(ism);
		addDsmOriginalSQLs(DsmOriginalSQLs.parse(ism));
	}
	
	public DsmSQLProvider getDsmSQLProvider(DataSource ds) {
		return getDsmSQLProvider(DbUtils.getDatabaseProduceName(ds));
	}
	
	public DsmSQLProvider getDsmSQLProvider(Connection conns) {
		return getDsmSQLProvider(DbUtils.getDatabaseProduceName(conns));
	}
	
	public DsmSQLProvider getDsmSQLProvider(String dspName) {
		dspName = dspName.trim().toLowerCase();
		for (DsmOriginalSQLs dsmSQLInfo : dsmOriginalSQLs) {
			if (dspName.startsWith(dsmSQLInfo.getSqlSupportProduct().toLowerCase())) {
				return new DsmSQLProviderImpl(dsmSQLInfo);
			}
		}
		throw new IllegalStateException(String.format("not support %s db", dspName));
	}

}
